package ui.panels;

import entities.Patient;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import manager.AdminBusiDriver;
import model.EditPatientTableModel;
import ui.windows.RemedySchedulerFrame;
import ui.windows.ViewPatientDialog;

public class PatientManagementPanel extends javax.swing.JPanel {

    /** Creates new form PatientManagementPanel */
    public PatientManagementPanel(RemedySchedulerFrame mainFrame) {
        initComponents();
        this.mainFrame = mainFrame;
        includeModel();
    }

    private void includeModel() {
        driver = (AdminBusiDriver) mainFrame.getDriver();
        model = new EditPatientTableModel(driver.showPatient());
        patientTable.setModel(model);
        patientTable.setFillsViewportHeight(true);
        patientTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        patientTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        patientTable.getTableHeader().setFont(new Font(null, Font.BOLD, 10));
        patientTable.getColumnModel().getColumn(0).setPreferredWidth(70);
        patientTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        patientTable.getColumnModel().getColumn(2).setPreferredWidth(50);        
        patientTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        patientTable.getColumnModel().getColumn(4).setPreferredWidth(200);
        patientTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        patientTable.getColumnModel().getColumn(6).setPreferredWidth(80);        

        createPatientPanel = new CreatePatientPanel(this);
        editPatientPanel = new EditPatientPanel(this);
        target = 1;
    }

    private void swithAction() {
        int choise = cbActions.getSelectedIndex();
        switchTarget(choise);
        cbActions.setSelectedIndex(0);
    }

    private void switchTarget(int choise) {
        if (target != choise || target == 4) {
            switch (choise) {
                case 0:
                    break;
                case 1:
                    this.remove(viewControl);
                    txtID.setEnabled(true);
                    txtName.setEnabled(true);
                    viewControl = new JScrollPane(patientTable);
                    target = 1;
                    this.add(viewControl, BorderLayout.CENTER);
                    this.revalidate();
                    break;
                case 2:
                    this.remove(viewControl);
                    txtID.setEnabled(false);
                    txtName.setEnabled(false);
                    viewControl = new JScrollPane(createPatientPanel);
                    target = 2;
                    this.add(viewControl, BorderLayout.CENTER);
                    this.revalidate();
                    break;
                case 3:
                    if (selectedPatient != null) {
                        this.remove(viewControl);
                        editPatientPanel.setPatient(selectedPatient);
                        viewControl = new JScrollPane(editPatientPanel);
                        this.add(viewControl, BorderLayout.CENTER);
                        this.revalidate();
                        target = 3;
                    } else {
                        JOptionPane.showMessageDialog(null, "You migh select one patient !");
                    }
                    break;
                case 4:
                    new Thread() {

                        @Override
                        public void run() {
                            deletePatient();
                        }
                    }.start();
                    break;
            }
        }
    }

    public void showAllPatient() {
        switchTarget(1);
    }

    public void showCreatePatient() {
        switchTarget(2);
    }

    public boolean createPatient(Patient patient) {
        boolean returnVal = driver.insertPatient(patient);
        if (returnVal) {
            patient.setModifiedDate(Calendar.getInstance().getTime());
            model.addElement(patient);
        }
        return returnVal;
    }

    public boolean updatePatient(Patient patient) {
        boolean returnVal = driver.updatePatient(patient);
        if (returnVal) {
            patient.setModifiedDate(Calendar.getInstance().getTime());
            model.update(patient);
        }
        return returnVal;
    }

    private void deletePatient() {
        int[] rows = patientTable.getSelectedRows();
        if (rows != null && rows.length == 1) {
            target = 4;
            int choise = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete this patient !", "Delete", JOptionPane.YES_NO_OPTION);
            if (choise == JOptionPane.YES_OPTION) {
                boolean returnVal = driver.deletePatient(selectedPatient);
                if (returnVal) {
                    model.remove(selectedPatient);
                    JOptionPane.showMessageDialog(this, "Deleted");
                } else {
                    JOptionPane.showMessageDialog(this, "Cannot delete !", "Error", JOptionPane.WARNING_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "You migh select one patient !", "Message", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public boolean containtID(String id) {
        return model.containtID(id);
    }

    private void filter() {
        model.filter(txtID.getText(), txtName.getText());
    }

    private void setSelectedPatient(java.awt.event.MouseEvent evt) {
        int index = patientTable.getSelectedRow();
        if (index != -1) {
            selectedPatient = model.getAt(index);
            editPatientPanel.setPatient(selectedPatient);
            if(evt.getClickCount() == 2) {
                ViewPatientDialog dialog = new ViewPatientDialog(mainFrame);
                dialog.setPatient(selectedPatient);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
            }
        } else {
            selectedPatient = null;
        }
    }

    public void closeTarget() {
        switchTarget(1);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtID = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        cbActions = new javax.swing.JComboBox();
        viewControl = new javax.swing.JScrollPane();
        patientTable = new javax.swing.JTable();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new java.awt.BorderLayout());

        jLabel1.setText("IdentityCard:");

        txtID.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtIDCaretUpdate(evt);
            }
        });

        jLabel2.setText("Name:");

        txtName.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtNameCaretUpdate(evt);
            }
        });

        cbActions.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Actions", "View All", "Add", "Edit", "Delete" }));
        cbActions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbActionsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                .addComponent(cbActions, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbActions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.PAGE_START);

        viewControl.setBackground(new java.awt.Color(255, 255, 255));

        patientTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        patientTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                patientTableMouseClicked(evt);
            }
        });
        viewControl.setViewportView(patientTable);

        add(viewControl, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

private void cbActionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbActionsActionPerformed
    swithAction();
}//GEN-LAST:event_cbActionsActionPerformed

private void txtIDCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtIDCaretUpdate
    filter();
}//GEN-LAST:event_txtIDCaretUpdate

private void txtNameCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtNameCaretUpdate
    filter();
}//GEN-LAST:event_txtNameCaretUpdate

private void patientTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_patientTableMouseClicked
    setSelectedPatient(evt);
}//GEN-LAST:event_patientTableMouseClicked
    private RemedySchedulerFrame mainFrame;
    private EditPatientTableModel model;
    private AdminBusiDriver driver;
    private CreatePatientPanel createPatientPanel;
    private EditPatientPanel editPatientPanel;
    private Patient selectedPatient;
    private int target;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbActions;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTable patientTable;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    private javax.swing.JScrollPane viewControl;
    // End of variables declaration//GEN-END:variables
}
